package com.topcent.tioxyc.consumer;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.LoadingCache;
import com.rabbitmq.client.Channel;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.mapper.Yy1KpiMapper;
import com.topcent.tioxyc.pojo.*;
import com.topcent.tioxyc.pojo.vo.CustomerPayVO;
import com.topcent.tioxyc.pojo.vo.DepartmentVO;
import com.topcent.tioxyc.pojo.vo.Lin;
import com.topcent.tioxyc.pojo.vo.SkNoVO;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * @author: 陈百万
 * @date: 2025/11/13 14:28
 * @Description: 客户预存款核销单
 */
@Component
@RabbitListener(queues = "PaymentTracking")
@Slf4j
public class PaymentTrackingConsumer {
    @Autowired
    private Yy1KpiMapper yy1KpiMapper;
    // ========== 新增：缓存配置（高频数据缓存） ==========
    // 人员信息缓存（6小时过期）
    private final LoadingCache<String, Map<String, String>> userNameCache = Caffeine.newBuilder()
            .expireAfterWrite(6, TimeUnit.HOURS)
            .build(key -> loadUserNameMap());

    // 部门信息缓存（6小时过期）
    private final LoadingCache<String, Map<String, Integer>> deptMapCache = Caffeine.newBuilder()
            .expireAfterWrite(6, TimeUnit.HOURS)
            .build(key -> loadDeptMap());

    // 客户主数据缓存（6小时过期）
    private final LoadingCache<String, Map<String, List<CustomerPayVO>>> customerCache = Caffeine.newBuilder()
            .expireAfterWrite(6, TimeUnit.HOURS)
            .build(key -> getCustomerListFromApi());

    @Lazy
    @Autowired
    private ThreadPoolTaskExecutor businessExecutor;

    private static final String DATA_CREATE = "data_create";
    private static final String DATA_UPDATE = "data_update";

    @RabbitHandler
    public void handleMessage(String msg, Channel channel, Message message) throws IOException {
        try {
            // 2. 提交核心逻辑到异步线程执行，接口立即返回success
            businessExecutor.submit(() -> {
                try {
                    handleData(msg);
                } catch (Exception e) {
                    log.error("异步处理简道云推送失败，payload:{}", msg, e);
                }
            });

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("Message acknowledged");
        } catch (Exception e) {
            // 处理异常并拒绝消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            System.err.println("发送消息失败，重试中 " + e.getMessage());
        }
    }

    // ========== 新增：缓存加载方法（原有高频查询逻辑迁移至此） ==========
    /** 加载人员信息到缓存 */
    private Map<String, String> loadUserNameMap() {
        log.info("加载人员信息到缓存");
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> person = new HashMap<>();
        person.put("dept_no", 1);
        person.put("has_child", true);
        JSONObject personResult = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/corp/department/user/list", headers, JSONUtil.toJsonStr(person));
        String personData = personResult.getStr("users");
        JSONArray personObjects = JSONUtil.parseArray(personData);
        List<Assignee> personList = JSONUtil.toList(personObjects, Assignee.class);
        return personList.stream()
                .collect(Collectors.toMap(Assignee::getName, Assignee::getUsername, (v1, v2) -> v1));
    }

    /** 加载部门信息到缓存 */
    private Map<String, Integer> loadDeptMap() {
        log.info("加载部门信息到缓存");
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> cond = new HashMap<>();
        cond.put("dept_no", 1);
        cond.put("has_child", true);
        JSONObject deptResult = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/corp/department/list", headers, JSONUtil.toJsonStr(cond));
        String deptData = deptResult.getStr("departments");
        JSONArray objects = JSONUtil.parseArray(deptData);
        List<DepartmentVO> deptList = JSONUtil.toList(objects, DepartmentVO.class);
        return deptList.stream()
                .collect(Collectors.toMap(DepartmentVO::getName, DepartmentVO::getDept_no, (v1, v2) -> v1));
    }

    /** 加载客户主数据到缓存（原有getCustomerList逻辑迁移） */
    private Map<String, List<CustomerPayVO>> getCustomerListFromApi() {
        log.info("加载客户主数据到缓存");
        List<CustomerPayVO> customerList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", "66a6f42ff97af74b02d217df");
        parameter.put("entry_id", "66a6f443333584e2c128154f");
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<CustomerPayVO> list = JSONUtil.toList(objects, CustomerPayVO.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            customerList.addAll(list);
        } while (fale);
        return customerList.stream()
                .collect(Collectors.groupingBy(customer -> customer.get_widget_1722305048887().trim()));
    }

    public List<Lin> getSkdId(String skNo, String appId, String entryId, String txt) {
        List<Lin> linList = new ArrayList<>();
        Header[] headers = ConnmeUtils.createHeaders();
        Map<String, Object> parameter = new HashMap<>();
        parameter.put("app_id", appId);
        parameter.put("entry_id", entryId);
        Map<String, Object> filter = new HashMap<>();
        filter.put("rel", "and");
        Map<String, Object> cond = new HashMap<>();
        cond.put("field", txt);
        cond.put("type", "text");
        cond.put("method", "eq");
        List<String> values = new ArrayList<>();
        values.add(skNo);
        cond.put("value", values);
        List<Map<String, Object>> conds = new ArrayList<>();
        conds.add(cond);
        filter.put("cond", conds);
        parameter.put("filter", filter);
        boolean fale = true;
        String zh = "";
        do {
            if (!zh.isEmpty()) {
                parameter.put("data_id", zh);
            }
            parameter.put("limit", 100);
            String jsonSale = JSONUtil.toJsonStr(parameter);
            JSONObject jdySale = ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/list", headers, jsonSale);
            String data = jdySale.getStr("data");
            JSONArray objects = JSONUtil.parseArray(data);
            List<Lin> list = JSONUtil.toList(objects, Lin.class);
            if (list.size() == 100) {
                zh = list.getLast().get_id();
            } else {
                fale = false;
            }
            linList.addAll(list);
        } while (fale);
        return linList;
    }


    // ========== 原有方法（仅修改：缓存获取高频数据） ==========
    private void handleData(String payload) {
        JSONObject payloadJSON = JSONUtil.parseObj(payload);
        String op = payloadJSON.getStr("op");
        String data = payloadJSON.getStr("data");
        if (DATA_CREATE.equals(op)) {
            changeManey(data);
        }
    }

    private void changeManey(String data) {
        Header[] headers = ConnmeUtils.createHeaders();
        CustomerPreDepositEntity customerPreDeposit = JSONUtil.toBean(data, CustomerPreDepositEntity.class);
        Map<String, DeliveryDocumentsEntity> documentsEntityMap = selectDeliveryData(); // 数据库查询（保持不变）
        List<CustomerPreDepositEntity.WriteOffDetail> salesNoList = customerPreDeposit.get_widget_1759994855383();
        List<CustomerPreDepositEntity.Receipt> receiptList = customerPreDeposit.get_widget_1759980545183(); // 收款单数据

        // 基础数据赋值（保持不变）
        Date gzDate = receiptList.getFirst().get_widget_1759980545185();
        String skNo = receiptList.getFirst().get_widget_1759980545186();
        BigDecimal noDecimal = receiptList.getFirst().get_widget_1759980545196();

        // 从缓存获取高频数据（保持不变）
        Map<String, String> userNameMap = userNameCache.get("USER_MAP");
        Map<String, Integer> deptMap = deptMapCache.get("DEPT_MAP");
        Map<String, List<CustomerPayVO>> customerList = customerCache.get("CUSTOMER_LIST");

        // 客户信息匹配（保持不变）
        CustomerPayVO customerPayVO = Optional.ofNullable(customerList)
                .map(map -> map.get(customerPreDeposit.get_widget_1760510976546()))
                .filter(list -> !list.isEmpty())
                .map(List::getFirst)
                .orElse(null);

        // 循环处理销售单（关键修改：移除外层if判断，改为允许deliveryDocumentsEntity为null）
        int no = 0;
        for (CustomerPreDepositEntity.WriteOffDetail writeOffDetail : salesNoList) {
            BigDecimal decimal5191 = writeOffDetail.get_widget_1759994855390();  // 汇率
            BigDecimal decimal5197 = writeOffDetail.get_widget_1759994855394(); // 累计核销金额
            BigDecimal decimal5197s = decimal5191.multiply(decimal5197);
            PaymentTrackingEntity resultEntity = new PaymentTrackingEntity();
            String salesNo = writeOffDetail.get_widget_1759994855386();
            // 1. 获取deliveryDocumentsEntity（可能为null）
            DeliveryDocumentsEntity deliveryDocumentsEntity = documentsEntityMap.get(salesNo);

            // 2. 赋值依赖deliveryDocumentsEntity的字段（优化组合编号逻辑）
            String addNo = null;
            // 分情况判断：优先组合，再单独值，最后null
            if (deliveryDocumentsEntity != null) {
                // 情况1：deliveryDocumentsEntity存在 → 拼接（需确保deliveryDocument非空）
                String deliveryDocument = deliveryDocumentsEntity.getDeliveryDocument();
                if (deliveryDocument != null && !deliveryDocument.trim().isEmpty() && salesNo != null && !salesNo.trim().isEmpty()) {
                    addNo = deliveryDocument + "-" + salesNo;
                } else if (salesNo != null && !salesNo.trim().isEmpty()) {
                    // 拼接条件不足，但销售单号有值 → 单独用销售单号
                    addNo = salesNo;
                }
            } else {
                // 情况2：deliveryDocumentsEntity为null → 销售单号有值则单独用，否则null
                if (salesNo != null && !salesNo.trim().isEmpty()) {
                    addNo = salesNo;
                }
            }
            resultEntity.set_widget_1760327721440(addNo); // 组合编号：有值则赋值，否则null

            // 其他依赖字段：存在时取实际值，否则null/空
            resultEntity.set_widget_1759202420873(
                    deliveryDocumentsEntity != null ? deliveryDocumentsEntity.getPlant() : null
            );
            resultEntity.set_widget_1759202420874(
                    deliveryDocumentsEntity != null ? deliveryDocumentsEntity.getActualGoodsMovementDate() : null
            );
            // 部门
            resultEntity.set_widget_1759202420875(Integer.parseInt(writeOffDetail.get_widget_1759994855387().getDept_no()));
            resultEntity.set_widget_1759202420876(writeOffDetail.get_widget_1759994855388().getUsername());
            resultEntity.set_widget_1759203125359(customerPreDeposit.get_widget_1760510976546());
            resultEntity.set_widget_1759203125360(receiptList.getFirst().get_widget_1760338973558());
            resultEntity.set_widget_1759203125361(
                    deliveryDocumentsEntity != null ? deliveryDocumentsEntity.getDeliveryDocument() : null
            );
            resultEntity.set_widget_1759203125362(writeOffDetail.get_widget_1759994855386());
            resultEntity.set_widget_1759203125364(receiptList.getFirst().get_widget_1759980545190());
            resultEntity.set_widget_1759203125365(
                    deliveryDocumentsEntity != null ? deliveryDocumentsEntity.getAmount1() : null
            );
            resultEntity.set_widget_1759203125366(
                    deliveryDocumentsEntity != null ? deliveryDocumentsEntity.getAmount3() : null
            );

            // 3. 客户相关字段（保持不变）
            int dayNum = 0;
            if (customerPayVO != null) {
                resultEntity.set_widget_1759203125367(customerPayVO.get_widget_1723200599102());
                resultEntity.set_widget_1760423989808(customerPayVO.get_widget_1723200599103());
                resultEntity.set_widget_1759203125369(customerPayVO.get_widget_1760518728455());
                // 避免空指针：如果客户付款天数字段为null，dayNum设为0
                if (resultEntity.get_widget_1759203125369() != null) {
                    dayNum = Integer.parseInt(resultEntity.get_widget_1759203125369());
                }
            }

            // 4. 应回款时间计算（依赖actualGoodsMovementDate，为null时不计算）
            Date actualGoodsMovementDate = deliveryDocumentsEntity != null ? deliveryDocumentsEntity.getActualGoodsMovementDate() : null;
            Date duePaymentDate = null;
            if (actualGoodsMovementDate != null && dayNum > 0) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(actualGoodsMovementDate);
                calendar.add(Calendar.DAY_OF_MONTH, dayNum);
                duePaymentDate = calendar.getTime();
            }
            resultEntity.set_widget_1759203125374(duePaymentDate);

            // 5. 应回款月份计算（保持不变，依赖duePaymentDate）
            Date duePaymentMonthDate = null;
            if (duePaymentDate != null) {
                Calendar utcCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
                utcCalendar.setTime(duePaymentDate);
                utcCalendar.set(Calendar.DAY_OF_MONTH, 1);
                utcCalendar.set(Calendar.HOUR_OF_DAY, 0);
                utcCalendar.set(Calendar.MINUTE, 0);
                utcCalendar.set(Calendar.SECOND, 0);
                utcCalendar.set(Calendar.MILLISECOND, 0);
                duePaymentMonthDate = utcCalendar.getTime();
            }
            resultEntity.set_widget_1759203125375(duePaymentMonthDate);

            // 6. 实际回款时间及月份（保持不变）
            resultEntity.set_widget_1759203125376(gzDate);
            Date actualPaymentMonthDate = null;
            if (gzDate != null) {
                Calendar utcCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
                utcCalendar.setTime(gzDate);
                utcCalendar.set(Calendar.DAY_OF_MONTH, 1);
                utcCalendar.set(Calendar.HOUR_OF_DAY, 0);
                utcCalendar.set(Calendar.MINUTE, 0);
                utcCalendar.set(Calendar.SECOND, 0);
                utcCalendar.set(Calendar.MILLISECOND, 0);
                actualPaymentMonthDate = utcCalendar.getTime();
            }
            resultEntity.set_widget_1759203125377(actualPaymentMonthDate);

            // 7. 回款情况（保持不变，不依赖deliveryDocumentsEntity）
            BigDecimal noBigDecimal = writeOffDetail.get_widget_1759994855395();
            BigDecimal actualNoAmount = noBigDecimal == null ? BigDecimal.ZERO : noBigDecimal;
            String paymentStatus = actualNoAmount.compareTo(BigDecimal.ZERO) > 0 ? "未结清" : "正常回款";
            resultEntity.set_widget_1759203125368(paymentStatus);

            // 8. 跟进人匹配（保持不变）
            Map<String, String> deptPersonMap = new HashMap<>();
            deptPersonMap.put("DIY销售部", "陈丽娜");
            deptPersonMap.put("ECO贸易销售部", "陈丽娜");
            deptPersonMap.put("ECO应用销售部", "张艳清");
            deptPersonMap.put("OBM销售部", "张艳清");
            deptPersonMap.put("PRO欧美销售部", "张艳清");
            deptPersonMap.put("PRO亚非销售部", "张艳清");
            deptPersonMap.put("BCP东南亚销售部", "陈丽娜");
            deptPersonMap.put("BCP美澳销售部", "陈丽娜");
            deptPersonMap.put("BCP欧亚销售部", "陈丽娜");
            deptPersonMap.put("BCP中非销售部", "张艳清");
            String deptName = "";
            if (writeOffDetail.get_widget_1759994855387() != null) {
                deptName = writeOffDetail.get_widget_1759994855387().getName();
            }
            String personCharge = deptPersonMap.getOrDefault(deptName, "待分配");
            resultEntity.set_widget_1760423176427(userNameMap.get(personCharge));

            // 9. 逾期判断（保持不变）
            Date currentDate = new Date();
            String overdueJudge = "";
            String overdueDays = "";
            if (gzDate != null) {
                long gzTime = gzDate.getTime();
                long currentTime = currentDate.getTime();
                if (gzTime > currentTime) {
                    overdueJudge = "不算";
                    overdueDays = "未逾期";
                } else {
                    overdueJudge = "算";
                    long timeDiff = currentTime - gzTime;
                    long daysDiff = timeDiff / (1000 * 60 * 60 * 24);
                    if (timeDiff % (1000 * 60 * 60 * 24) != 0) {
                        daysDiff++;
                    }
                    overdueDays = String.valueOf(daysDiff);
                }
            } else {
                overdueJudge = "未回款";
                overdueDays = "未回款";
            }
            resultEntity.set_widget_1759203125379(overdueJudge);
            resultEntity.set_widget_1759203125381(overdueDays);

            // 10. 金额相关赋值（依赖deliveryDocumentsEntity的amount3，为null时用BigDecimal.ZERO）
            BigDecimal amount3 = deliveryDocumentsEntity != null ? deliveryDocumentsEntity.getAmount3() : BigDecimal.ZERO;
            resultEntity.set_widget_1759203125370(decimal5197);
            resultEntity.set_widget_1759203125371(decimal5197s);
            resultEntity.set_widget_1759203125372(amount3.subtract(decimal5197s));

            // 11. 插入收款追踪表（无论是否有deliveryDocumentsEntity，都执行）
            no++;
            Map<String, Object> parameterFix = new HashMap<>();
            parameterFix.put("app_id", "669cb709a73cc1289c49800e");
            parameterFix.put("entry_id", "68db4c7420407efb3e3bc238");
            parameterFix.put("data", ConnmeUtils.convertEntityToMap(resultEntity));
            resultEntity.set_id(null);
            String jsonSale = JSONUtil.toJsonStr(parameterFix);
            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/create", headers, jsonSale);
            System.out.println("收款追踪循环了" + no + "次数");

            // 12. 销售单金额更新（保持不变，即使deliveryDocumentsEntity为null也执行）
            List<Lin> xsLinList = getSkdId(salesNo,"667230ad22a8581756b77d52","667230b322a8581756b78353","_widget_1718759603973");
            if (xsLinList.isEmpty()) {
                log.error("未找到销售单号{}对应的销售单ID", salesNo);
                continue;
            }
            String xsId = xsLinList.getLast().get_id();
            SkNoVO vo = new SkNoVO();
            vo.set_id(xsId);
            vo.set_widget_1760062072774(noBigDecimal);
            vo.set_widget_1760062072775(noBigDecimal);
            Map<String, Object> parameterInster = new HashMap<>();
            parameterInster.put("app_id", "667230ad22a8581756b77d52");
            parameterInster.put("entry_id", "667230b322a8581756b78353");
            parameterInster.put("is_start_trigger", "true");
            parameterInster.put("data_id", vo.get_id());
            vo.set_id(null);
            parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(vo));
            String jsonSalee = JSONUtil.toJsonStr(parameterInster);
            ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
        }

        // 收款单金额更新（保持不变）
        List<Lin> skLinList = getSkdId(skNo,"669cb709a73cc1289c49800e","669cb70dab60aa3f4a7bb8b2","_widget_1721705341229");
        if (skLinList.isEmpty()) {
            log.error("未找到收款单号{}对应的收款单ID", skNo);
            return;
        }
        String skId = skLinList.getFirst().get_id();
        SkNoVO vo = new SkNoVO();
        vo.set_id(skId);
        vo.set_widget_1760338419357(noDecimal);
        vo.set_widget_1760337092551(noDecimal);
        Map<String, Object> parameterInster = new HashMap<>();
        parameterInster.put("app_id", "669cb709a73cc1289c49800e");
        parameterInster.put("entry_id", "669cb70dab60aa3f4a7bb8b2");
        parameterInster.put("is_start_trigger", "true");
        parameterInster.put("data_id", vo.get_id());
        vo.set_id(null);
        parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(vo));
        String jsonSalee = JSONUtil.toJsonStr(parameterInster);
        ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/update", headers, jsonSalee);
    }

    public Map<String, DeliveryDocumentsEntity> selectDeliveryData() {
        List<DeliveryDocumentsEntity> originalData = yy1KpiMapper.selecDeliveryDocumentsDatatAll();
        Map<String, DeliveryDocumentsEntity> resultMap = new HashMap<>();
        for (DeliveryDocumentsEntity data : originalData) {
            String groupKey = data.getReferenceSDDocument();
            if (groupKey == null || groupKey.trim().isEmpty()) {
                groupKey = "未知销售凭证";
            }
            if (!resultMap.containsKey(groupKey)) {
                DeliveryDocumentsEntity newEntity = new DeliveryDocumentsEntity();
                copyNonAmountFields(data, newEntity);
                newEntity.setAmount1(convertNullToZero(data.getAmount1()));
                newEntity.setNetAmount1(convertNullToZero(data.getNetAmount1()));
                newEntity.setAmount2(convertNullToZero(data.getAmount2()));
                newEntity.setNetAmount2(convertNullToZero(data.getNetAmount2()));
                newEntity.setAmount3(convertNullToZero(data.getAmount3()));
                newEntity.setNetAmount3(convertNullToZero(data.getNetAmount3()));
                resultMap.put(groupKey, newEntity);
            } else {
                DeliveryDocumentsEntity existingEntity = resultMap.get(groupKey);
                existingEntity.setAmount1(existingEntity.getAmount1().add(convertNullToZero(data.getAmount1())));
                existingEntity.setNetAmount1(existingEntity.getNetAmount1().add(convertNullToZero(data.getNetAmount1())));
                existingEntity.setAmount2(existingEntity.getAmount2().add(convertNullToZero(data.getAmount2())));
                existingEntity.setNetAmount2(existingEntity.getNetAmount2().add(convertNullToZero(data.getNetAmount2())));
                existingEntity.setAmount3(existingEntity.getAmount3().add(convertNullToZero(data.getAmount3())));
                existingEntity.setNetAmount3(existingEntity.getNetAmount3().add(convertNullToZero(data.getNetAmount3())));
            }
        }
        return resultMap;
    }

    private void copyNonAmountFields(DeliveryDocumentsEntity source, DeliveryDocumentsEntity target) {
        target.setDeliveryDocument(source.getDeliveryDocument());
        target.setReferenceSDDocument(source.getReferenceSDDocument());
        target.setActualGoodsMovementDate(source.getActualGoodsMovementDate());
        target.setConditionCurrency(source.getConditionCurrency());
        target.setSoldToParty(source.getSoldToParty());
        target.setBusinessPartnerName1(source.getBusinessPartnerName1());
        target.setYY1_divison_seller_DLH(source.getYY1_divison_seller_DLH());
        target.setSalesOfficeName(source.getSalesOfficeName());
        target.setPlant(source.getPlant());
    }

    private BigDecimal convertNullToZero(BigDecimal value) {
        return value == null ? BigDecimal.ZERO : value;
    }

}
